﻿
Imports System.Configuration


Namespace Configuration



    ''' <summary>
    ''' 节配置管理器(泛型)
    ''' </summary>
    ''' <remarks></remarks>
    Public NotInheritable Class SectionManager



        Private Sub New()
        End Sub

        ''' <summary>
        ''' 是否存在 配置信息
        ''' </summary>
        ''' <param name="sectionName"> 配置节名称</param>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared ReadOnly Property HaveSection(ByVal sectionName As String) As Boolean
            Get
                'Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                'If config.HasFile Then
                '    For Each name As String In config.Sections.Keys
                '        If name = sectionName Then Return True
                '    Next
                'End If

                Dim setting = ConfigurationManager.GetSection(sectionName)

                If setting IsNot Nothing Then Return True

                Return False
            End Get
        End Property

        ''' <summary>
        ''' 获取设置
        ''' </summary>
        ''' <param name="sectionName"> 配置节名称</param>
        ''' <typeparam name="T">返回 Section的类型</typeparam>
        ''' <returns>如果不存在，则返回空</returns>
        ''' <remarks></remarks>
        Public Shared Function GetSection(Of T As ConfigurationSection)(ByVal sectionName As String) As T

            ConfigurationManager.RefreshSection(sectionName)

            ' Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

            'Return TryCast(config.GetSection(sectionName), T)
            Return TryCast(ConfigurationManager.GetSection(sectionName), T)
        End Function

        ''' <summary>
        ''' 保存设置
        ''' </summary>
        ''' <param name="sectionName"> 配置节名称</param>
        ''' <param name="value">设置参数</param>
        ''' <typeparam name="T">要保存Section的类型</typeparam>
        ''' <remarks></remarks>
        Public Shared Sub SaveSection(Of T As ConfigurationSection)(ByVal sectionName As String, ByVal value As T)

            ConfigurationManager.RefreshSection(sectionName)

            Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)


            If HaveSection(sectionName) Then
                config.Sections.Remove(sectionName)
            End If

            config.Sections.Add(sectionName, value)

            config.Save()
        End Sub

    End Class



End Namespace